package com.wistech.search.solr.extend.service;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import javax.annotation.PostConstruct;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.wistech.search.solr.extend.dao.ProductDao;
import com.wistech.search.solr.extend.model.Product;

@Service
public class ProductManager {
	@Autowired
	private ProductDao productDao;
	private Map<String, Float> scores = new ConcurrentHashMap<String, Float>();
	private Map<String, Float> orderNums = new ConcurrentHashMap<String, Float>();

	public Product getProduct(String id) {
		return productDao.get(id);
	}

	public void saveProduct(Product product) {
		productDao.save(product);
		// 更新cache中的score
		if (product.getScore() != 0f) {
			scores.put(product.getId(), product.getScore());
		} else {
			scores.remove(product.getId());
		}
		// 更新cache中的orderNum
		if (product.getOrderNum() != 0) {
			orderNums.put(product.getId(),
					new Integer(product.getOrderNum()).floatValue());
		} else {
			orderNums.remove(product.getId());
		}
	}

	public void deleteProduct(String id) {
		if (id == null)
			return;
		productDao.delete(id);
		scores.remove(id);
		orderNums.remove(id);
	}

	@PostConstruct
	public void loadProductScores() {
		Map<String, Float> scores = new ConcurrentHashMap<String, Float>();
		scores.putAll(productDao.getAllScores());
		this.scores = scores;
	}

	public float getProductScore(String id) {
		Float score = scores.get(id);
		if (score != null) {
			return score;
		} else {
			score = productDao.getScore(id);
			if (score == null) {
				return 0f;
			}
			scores.put(id, score);
			return score;
		}
	}

	@PostConstruct
	public void loadProductOrderNums() {
		Map<String, Float> orderNums = new ConcurrentHashMap<String, Float>();
		orderNums.putAll(productDao.findOrderNums());
		this.orderNums = orderNums;
	}

	public Map<String, Float> getAllProductOrderNums() {
		return orderNums;
	}

}
